import { debounce } from "@/utils";

// const GOOGLE_DEVIATION = 3; // 在 google 浏览器上偏差了 1px，这里设置为 3
const MIN_DIFF = 3; // 距离底部多少距离的时候触发加载事件

export default {
  data() {
    return {
      showScrollLoading: false, // 是否正在加载滚动数据
      appendParentElement: null, // 需要追加 loading box 的父级元素
      appendLoadingElement: null // 需要追加的 loading box
    };
  },
  watch: {
    showScrollLoading(loading) {
      if (!this.appendParentElement) {
        const element = document.querySelector(this.appendSelector);
        if (!element) {
          return this.$message.error("元素不存在");
        }
        this.appendParentElement = element;
      }
      let box = this.appendLoadingElement;
      if (loading) {
        // 正在加载
        if (!box) {
          box = document.createElement("div");
          box.style.cssText = "padding: 20px;text-align: center;";
          box.innerHTML = `
            <div class="loader"></div>
          `;
          this.appendLoadingElement = box;
        }
        return this.appendParentElement.appendChild(box);
      }
      // 加载完了
      this.appendParentElement.removeChild(box);
    }
  },
  mounted() {
    const body = document.documentElement || document.body;
    this.__scrollAction = debounce(() => {
      // 是否已经在加载
      if (this.showScrollLoading) return;
      const clientHeight = body.clientHeight;
      const scrollTop = body.scrollTop;
      const scrollHeight = body.scrollHeight;
      const scrollTotal = scrollTop + clientHeight;
      if (scrollTotal < scrollHeight - MIN_DIFF) {
        return;
      }
      this.infiniteScrollAction();
    });
    window.addEventListener("scroll", this.__scrollAction);
  },
  beforeDestroy() {
    window.removeEventListener("scroll", this.__scrollAction);
  }
};
